package ws

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
)

const (
	MSG_CMD_HEART  = 101
	MSG_CMD_SYSTEM = 0
	MSG_CMD_LOGIN  = 1
	MSG_CMD_CHAT   = 2
)

var clientManager WSClientManager = NewDefaultClientManager()

func HandlerWebsocket(ctx *gin.Context) {

	conn, err := (&websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}).Upgrade(ctx.Writer, ctx.Request, nil)

	if err != nil {
		http.NotFound(ctx.Writer, ctx.Request)
		return
	}

	go func() {
		for {
			var messageBox map[string]interface{}
			err := conn.ReadJSON(&messageBox)
			if err != nil {
				if closeErr, ok := err.(*websocket.CloseError); ok {
					fmt.Println("客户端连接断开", closeErr.Code)
				}
				break
			}
			// 跳过心跳检测数据包
			if messageBox["cmdType"].(float64) == 101 {
				continue
			}

			// 处理登录
			b := HandlerLogin(messageBox, conn)
			if b {
				break
			}
		}
	}()
}

type SendFN func(message string)

func HandlerLogin(msgbox map[string]interface{}, conn *websocket.Conn) bool {
	if msgbox["cmdType"].(float64) != MSG_CMD_LOGIN {
		return false
	}
	name := msgbox["name"].(string)
	client := NewClient(name, conn)
	go client.Start(clientManager)
	return true
}
